<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<html>
<head>
<title>角色管理-添加角色</title>
<jsp:include page="/common/head.jsp"></jsp:include>
<link href="<%=request.getContextPath()%>/static/plugin/zTree/css/zTreeStyle/zTreeStyle.css" rel="stylesheet">
<script src="<%=request.getContextPath()%>/static/plugin/zTree/js/jquery.ztree.all-3.5.min.js"></script>
<style>

.tree-wrap {
    position: static;
    border: 1px solid #e1e6eb;
    box-sizing: border-box;
    width: 250px;
    color: #212121;
}
.tree-title {
    border-bottom: 1px solid #e1e6eb;
    text-indent: 10px;
    background-color: #f5f8fa;
}
.tree-content {
    min-height: 360px; 
    height: 360px;  
    padding: 5px; 
    overflow: auto;
    position: static;
}
.left{
	float: left;
}
#wrap {
   overflow:hidden; 
}

</style>
</head>
<body class="iframe-page">
<div class="page-title-wrapper">
    <div class="page-title">
        <div class="page-title-text">
            <span>角色管理</span>
            <span class="split"></span>
            <span>新建角色</span>
        </div>
        <a id="goBack" class="btn-return distance-left" href="javascript:;"><i class="icon icon-arrow-left"></i>返回上级</a>
    </div>
    <div class="page-title-border"></div>
</div>

<div class="form-wrapper">
        <div class="form-cont">
            <p class="form-cont-title"><span class="field-required">*</span>角色名称</p>
            <input type="text" class="summer-input" id="roleName" name="name">
            <p class="label-secondary"></p>
        </div>
        
        <div class="form-cont">
            <p class="form-cont-title" style="float:left;">权限配置</p>
            <div id="wrap">
            <div class="tree-wrap left">
                <div class="tree-title">
                                    资源权限 
                </div>
                <div class="tree-content">
                   <ul id="resourceTree" class="ztree"></ul> 
                </div>
            </div>
            <div class="tree-wrap left" style="border-left: 0;background-color: #fafafa;">
                <div class="tree-title" style="color: #757575">
                                    从已有角色中复制 
                </div>
                <div class="tree-content">
                   <ul id="roleTree" class="ztree"></ul>
                </div>
            </div>
        </div>
        </div>
        
</div>



	<div class="form-btn-wrapper" id="funcbar">
		<!-- <a class="btn btn-normal btn-ok distance-right" id="saveBtn">保存</a> -->
	    <a class="btn btn-normal" id="closeBtn">关闭</a>
	</div>
<script>
var ROLE_CONST_URL = {
					        ADD : basePath + "/sys/role/add",
					        ROLETREE : basePath + '/sys/role/getRoleTree',
					        RESOURCETREE : basePath + '/sys/inner/resourceTree',
					        CHECKEXIST :basePath + "/sys/role/checkRoleExist",
					        ROLERESOURCETREE : basePath + "/sys/roleResource/getResourceByRole",
					        INIT: basePath + "/sys/role/init"
				      };
var permission = CommonUtil.getPermission('role');
var roleTree,resourceTree;   
$(function() {
	
      $('#funcbar').prepend($.funcbar({
          type: 'button',
          data: permission,
          permit: ['role:add']
      }));	
	   	
	   //表单提交事件
       $('#funcbar').on('click', 'a[data-permit="role:add"]', save);
       //加载角色树
       initRoleTree();
       //加载资源树
       initResourceTree(ROLE_CONST_URL.RESOURCETREE);
       //关闭按钮事件
       $('#closeBtn,#goBack').on('click',goBack);
       //校验角色名称是否存在		
	   validateExist('#roleName','name', ROLE_CONST_URL.CHECKEXIST, ['required','maxLength[30]', "chsNoSymbol", 'regexp'], "角色名可用");
});

//初始角色树
function initRoleTree() {
    var setting = {
        check : {
            enable : true ,
            chkStyle: "checkbox",
            chkboxType : { "Y" : "ps", "N" : "ps" }
        },
        data : {
            key : {
                name : "name"
            },
            simpleData : {
                enable : true,
                idKey : 'id',
                pIdKey : 'parentId'
            }
        },
        callback: {//选中或取消选中时调用事件
            onCheck: zTreeOnCheck,
            onClick: zTreeOnClick
        }
    };
    $.ajax({
        url : ROLE_CONST_URL.ROLETREE,
        success : function(data) {
        	roleTree = $.fn.zTree.init($("#roleTree"), setting, data.data);
        }
    });
}

//初始资源树
function initResourceTree(url) {
    var setting = {
        check : {
            enable : true,
            chkStyle: "checkbox",
            chkboxType : { "Y" : "ps", "N" : "ps" }
        },
        data : {
            key : {
                url : "zUrl",
            },
            simpleData : {
                enable : true,
                idKey : 'id',
                pIdKey : 'pId'
            }
        }
    };
    $.ajax({
        url : url,
        success : function(data) {
        	resourceTree = $.fn.zTree.init($("#resourceTree"), setting, data);
            var nodes = resourceTree.getNodes();
            if (nodes.length>0){ //展开资源树根节点
            	resourceTree.expandNode(nodes[0], true, false, true)  
            }
        }
    });
}
//选中角色树时触发
function zTreeOnCheck(event, treeId, treeNode) {
	roleTree.selectNode(treeNode);
	loadResourceTree();
};
//点击角色树时触发
function zTreeOnClick(event, treeId, treeNode) {
	roleTree.checkNode(treeNode, !treeNode.checked, true);
	loadResourceTree();
};

//重新加载资源树
function loadResourceTree(){
	var roleId = getChecked("roleTree"),//获取所有选中的角色树id
            src = null;
	//根据选中的角色id,重新加载资源树
	if(roleId){
	src = ROLE_CONST_URL.ROLERESOURCETREE+"?roleIds="+roleId
	}else{
	src = ROLE_CONST_URL.RESOURCETREE;
	}
	initResourceTree(src);
}
// 获得选中节点
function getChecked(id) {
    var treeObj = $.fn.zTree.getZTreeObj(id);
    var nodes = treeObj.getCheckedNodes(true);
    var resourceIds = [];
    $.each(nodes, function() {
        resourceIds.push(this.id);
    });
    return resourceIds.join(",");
}
//校验角色名称
function validate() {
    var validate = $("#roleName"),
    result = true;
    if (!validate.validatebox("validate",{"hideSuccessTooltip" : true})) {
        if (result) {
        	validate.focus();
        	validate.addClass('summer-validatebox-input-error');
            result = false;
        }
        return result;
    }
    return result;
}
//保存
function save() {
	var is_validate = validate();
	if(!is_validate){
		return is_validate;
	}
    $.sajax({
            url : ROLE_CONST_URL.ADD,
            data : {
                "resourceIds" : getChecked("resourceTree"),
                "name":$("#roleName").val()
            },
            type : "post",
            onLoadSuccess : function(data) {
            	if(data.result=="success"){
            		$.stip({
                        type:'ok',//显示类型 有info、 ok、 danger
                        text: '保存成功！',
                        onBeforeHide: function() {
                        	goBack();
                        }
                    });
            		
            	} 
            }
    });
}

//关闭
function goBack() {
	window.location.href=ROLE_CONST_URL.INIT;
}

//校验角色名称是否存在
function validateExist(id, name, url, validType, message) {
    $(id).validatebox({
        rules: {
            regexp: {
                validator: function (value,param) {
                    var result = false,
                        params = {}, 
                        key = name;
                        params[key] = value;
                        
                    $.ajax({
                        type: 'post',
                        url: url,
                        data: params,
                        dataType: 'json',
                        async: false,
                        success: function (data) {
                            if (data.result == 'exist') {
                                result = false;
                            } else {
                                result = true;
                            }
                        }
                    });
                    return result;
                },
                message: message,
            }
        },
        validType: validType
    });
}
</script>
</body>
</html>